package com.keith.jpa.tenant;

import com.google.common.base.Strings;
import com.keith.jpa.tenant.utils.TenantUtils;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import java.io.Serializable;

/**
 * TenantJpaEmptyInterceptor.java
 * 处理jpa实体保存的租户处理
 *
 * @author czykeih
 * @version 1.0 2023/10/25
 */
@Slf4j
public class TenantJpaEmptyInterceptor extends EmptyInterceptor {
    @Override
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        if (TenantUtils.checkCurrentTenantStatus()){
            String tableName = TenantUtils.getTableName(entity);
            if (TenantUtils.jpaConfig().isLog()) {
                log.info("当前操作对象映射表名:[{}]",tableName);
            }
            if(!Strings.isNullOrEmpty(tableName)&&TenantUtils.verifyTableName(tableName)){
                TenantUtils.transTenantId(entity,state,propertyNames);
            }
        }
        return super.onSave(entity, id, state, propertyNames, types);
    }
}
